<template>
  <!-- 商品列表 -->
  <div class="sort-list-container">
    <ul>
      <li v-for="good in goodList" :key="good.id">
        <GoodsItem :good="good" />
      </li>
    </ul>
    <XtxInfiniteLoad :isLoading="isLoading" :isFinished="isFinished" @load="loadNextPage"/>
  </div>
</template>

<script>
import GoodsItem from './second-good.vue'
import { findSubCategoryGoods } from '@/api/category'
import { inject, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
export default {
  name: 'SubList',
  components: {
    GoodsItem
  },
  setup () {
    // 商品列表
    const goodList = ref([])
    // 路由实例
    const route = useRoute()
    // 是否是加载状态
    const isLoading = ref(false)
    // 数据是否已加载完成
    const isFinished = ref(false)
    // 参数
    const reqParams = {
      page: 0,
      pageSize: 20,
      categoryId: route.params.id,
      sortField: null, // 排序类别
      attrs: [], // 商品属性
      brandId: null // 品牌名称
    }

    // 引入筛选参数
    const filterParams = inject('filterParams')
    // 监听筛选参数变化
    watch(() => filterParams.value, (newVal) => {
      // console.log(newVal)
      // 先将数据置空 在拿新的筛选条件 请求数据渲染
      goodList.value = []
      reqParams.page = 0
      isFinished.value = false
      // const newReqParams = { ...reqParams, ...newVal }
      // 重新调用获取商品列表函数
      // getGoodList(newReqParams)
    }, { deep: true })

    // 获取数据方法
    // const getGoodList = async (params) => {
    //   const { result } = await findSubCategoryGoods(params)
    //   console.log(result)
    //   goodList.value = result.items
    // }

    // 子传父 触发上拉加载
    const loadNextPage = async () => {
      // 修改加载状态
      isLoading.value = true
      // 页码+1
      reqParams.page++
      // 发送请求
      const { result } = await findSubCategoryGoods({ ...reqParams, ...filterParams })
      // 合并数据
      goodList.value.push(...result.items)
      // 关闭加载状态
      isLoading.value = false
      // 判断数据是否全部加载完
      if (goodList.value.length === result.counts) {
        isFinished.value = true
      }
    }

    // 调用
    // onMounted(() => {
    //   getGoodList(reqParams)
    // })

    return { goodList, isLoading, isFinished, loadNextPage }
  }
}
</script>

<style lang="less" scoped>
.sort-list-container {
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
